angular.module('Controller')

.controller('QgyCotenantManageCtrl', ($scope,NgTableParams,urls,userData,menuManage,wfAlert,$localStorage,commonUtil,commonConstant,$rootScope,$uibModal,$http) ->
    initSearchData = ()->
        $scope.search = {
            apartmentId:$localStorage['accountStore'],
            searchStr:undefined
            createTimeStart:undefined
            createTimeEnd:undefined
            contractStatus:8
        }
    initSearchData()
    $scope.enabledList=commonConstant.enabledList(true)
    $scope.payWayList=commonConstant.payWayList(true)
    $scope.contractStatusList=commonConstant.contractStatusList(true)
    $scope.appointmentStatusList=commonConstant.appointmentStatusList(true)
    $scope.sexList=commonConstant.qgySexList()
    $scope.leaseList=commonConstant.leaseList(true)
    $scope.cotenantStatusList=commonConstant.cotenantStatusList(true)
    loadApartment=()->
        $scope.apartmentList=[{id:undefined,name:'全部'}]
        $http.get('/apartment',params:{page:0,size:999,enabled:true})
        .success (resp)->
            if resp.code==0
                $scope.apartmentList=$scope.apartmentList.concat(resp.message.content)
            else
                console.log(resp.message)
        .error (err)->
            console.log(err)
    loadApartment()
    $scope.tableParams = new NgTableParams(
            {page: 1, count: commonConstant.pageTableCount},
            {
                counts: [5, 10, 20],
                getData: ($defer, params)->
                    $scope.doQuery($defer,params)
                    return ;
            }
    )


    $scope.doQuery=($defer, params)->

        reqData={
            page: params.page() - 1,
            size: params.count(),
            apartmentId:$scope.search.apartmentId,
            filter:$scope.search.searchStr,
            contractStatus:$scope.search.contractStatus
        }
        $scope.currentSearchData=angular.copy($scope.search)
        if $scope.search['createTimeStart']
            reqData['createTimeStart']=moment($scope.search['createTimeStart']).format('YYYY-MM-DD')
        if $scope.search['createTimeEnd']
            reqData['createTimeEnd']=moment($scope.search['createTimeEnd']).format('YYYY-MM-DD')
        $http.get('/cotenant',params:reqData)
        .success (resp)->
            if resp.code==0
                $scope.tableData=resp.message.content
                params.total(resp.message.totalElements)
                $defer.resolve($scope.tableData)
            else
                console.log(resp.message)
        .error (err)->
            console.log(err)
    _.extend $scope,
        newData:(item)->
            theData={
                contractId:item.contractId,
                contractNo:item.contractNo
                houseNo:item.houseNo
                sex:1
            }
            showModal('new',theData)
        editContractData:(item)->
            $http.get("/contract/#{item.contractId}/detail")
            .success((resp)->
                if resp.code==0
                    theData=angular.copy(resp.message)
                    showCotenantModal('edit',theData.cotenants,theData)
            )
        editData:(item)->
            theData=angular.copy(item)
            showModal('edit',theData)
        viewData:(item)->
            return
            theData=angular.copy(item)
            showModal('view',theData)
        goDetail:(item)->
            return
            $rootScope.pageType='contract-detail'
            $rootScope.pageParams={contractId:item.id}
            menuManage.goState('contract-detail',true)
        resetSearch: ->
            initSearchData()
        queryData: (keepPage)->
            if(keepPage != true)
                $scope.tableParams.page(1)
            $scope.tableParams.reload()
        removeData:(item)->
            $http.delete('/contract/'+item.id)
            .success((resp)->
                if resp.code==0
                    wfAlert.toastInfo('合同信息删除成功');
                    $scope.queryData();
                else
                    wfAlert.toastError(resp.message)
            )
        exportData:->
            $scope.exporting = true;
            data = $scope.currentSearchData;
            reqData={
                page: 0,
                size: 999999,
                apartmentId:data.apartmentId,
                filter:data.searchStr,
                contractStatus:data.contractStatus
            }
            if $scope.search['createTimeStart']
                reqData['createTimeStart']=moment(data['createTimeStart']).format('YYYY-MM-DD')
            if $scope.search['createTimeEnd']
                reqData['createTimeEnd']=moment(data['createTimeEnd']).format('YYYY-MM-DD')
            $http.get('/cotenant/excel',params:reqData)
            .success((resp)->
                $scope.exporting = false
                if resp.code == 0
                    filename = resp.message
                    url=urls.backend+'/cotenant/download?file=' + filename
                    url=url+'&token='+userData.getToken()
                    console.log('url',url)
                    window.open(url, '_blank')
            )
            .error((err)->
                $scope.exporting = false
            )
    showCotenantModal = (type, data,contract)->
        modal = $uibModal.open({
            animation: true,
            size: 'lg',
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyCotenantModalCtrl',
            templateUrl: 'templates/business-manage/cotenant-modal/cotenant-modal.html',
            resolve: {
                items: ()-> {type: type, data: data,contract:contract}
            }
        })
    showModal=(type,data)->
        $scope.modal = $uibModal.open({
            animation: true,
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyCotenantEditModal',
            templateUrl: 'templates/business-manage/cotenant-manage/cotenant-edit-modal.html',
            resolve: {
                items:  ()->{type: type, data: data}
            }
        })
        $scope.modal.result.then((modalData)->
            $scope.queryData()
        )
)